import { createWebHistory, createRouter } from "vue-router";
import routes from "@/routers/routes";
import NProgress from "nprogress";
import { getCurrentAdminInfo } from "@/api/login";
import loading from "@/tools/loading";
import { setAdmin } from "@/tools/cookieMgr";

const router = createRouter({
  history: createWebHistory(),
  routes,
});
// 导航守卫
router.beforeEach(async (to, _, next) => {
  NProgress.start();
  if (to.meta.not_check) {
    next();
  } else {
    const res = await getCurrentAdminInfo();
    if (res && res.code >= 0) {
      setAdmin(JSON.stringify(res.data));
      next();
    } else {
      next("/login");
    }
  }
});
router.afterEach(() => {
  // 关闭进度条并防止闪烁
  setTimeout(() => {
    loading.hide();
    NProgress.done();
  }, 200);
});

export default router;
